const jwt = require('jsonwebtoken');
const User = require('../models/User');

// Socket认证中间件
const authenticateSocket = async (socket, next) => {
  try {
    const token = socket.handshake.auth.token || socket.handshake.headers.authorization?.replace('Bearer ', '');
    
    if (!token) {
      return next(new Error('Authentication error'));
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await User.findById(decoded.id).select('-password');
    
    if (!user) {
      return next(new Error('User not found'));
    }

    socket.user = user;
    next();
  } catch (error) {
    console.error('Socket authentication error:', error);
    next(new Error('Authentication error'));
  }
};

const handleConnection = (io) => {
  // 使用认证中间件
  io.use(authenticateSocket);

  io.on('connection', (socket) => {
    console.log(`User ${socket.user.username} connected: ${socket.id}`);

    // 加入用户特定的房间
    socket.join(`user_${socket.user._id}`);
    socket.join(`role_${socket.user.role}`);

    // 发送欢迎消息
    socket.emit('welcome', {
      message: `欢迎 ${socket.user.username}`,
      user: {
        id: socket.user._id,
        username: socket.user.username,
        role: socket.user.role
      }
    });

    // 处理实时数据请求
    socket.on('request_realtime_data', () => {
      // 模拟实时数据
      const realtimeData = {
        timestamp: new Date().toISOString(),
        deviceStatus: {
          online: Math.floor(Math.random() * 100) + 50,
          offline: Math.floor(Math.random() * 20) + 5,
          warning: Math.floor(Math.random() * 10) + 1
        },
        energyConsumption: {
          current: Math.floor(Math.random() * 1000) + 500,
          today: Math.floor(Math.random() * 10000) + 5000,
          thisMonth: Math.floor(Math.random() * 100000) + 50000
        },
        parkingStatus: {
          total: 500,
          occupied: Math.floor(Math.random() * 400) + 100,
          available: Math.floor(Math.random() * 100) + 50
        },
        securityAlerts: Math.floor(Math.random() * 5)
      };

      socket.emit('realtime_data', realtimeData);
    });

    // 处理设备控制
    socket.on('device_control', (data) => {
      console.log(`Device control from ${socket.user.username}:`, data);
      
      // 广播设备状态变化给相关用户
      socket.broadcast.to(`role_${socket.user.role}`).emit('device_status_changed', {
        deviceId: data.deviceId,
        action: data.action,
        operator: socket.user.username,
        timestamp: new Date().toISOString()
      });

      // 确认操作
      socket.emit('device_control_result', {
        success: true,
        message: '设备控制成功',
        deviceId: data.deviceId
      });
    });

    // 处理告警确认
    socket.on('acknowledge_alert', (alertId) => {
      console.log(`Alert ${alertId} acknowledged by ${socket.user.username}`);
      
      // 广播告警确认给管理员
      io.to('role_admin').emit('alert_acknowledged', {
        alertId,
        acknowledgedBy: socket.user.username,
        timestamp: new Date().toISOString()
      });
    });

    // 处理断开连接
    socket.on('disconnect', (reason) => {
      console.log(`User ${socket.user.username} disconnected: ${reason}`);
    });

    // 错误处理
    socket.on('error', (error) => {
      console.error(`Socket error for user ${socket.user.username}:`, error);
    });
  });

  // 定时发送系统状态更新
  setInterval(() => {
    const systemStatus = {
      timestamp: new Date().toISOString(),
      cpuUsage: Math.random() * 100,
      memoryUsage: Math.random() * 100,
      diskUsage: Math.random() * 100,
      networkTraffic: Math.random() * 1000
    };

    io.to('role_admin').emit('system_status', systemStatus);
  }, 30000); // 每30秒发送一次
};

module.exports = { handleConnection };
